<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bug列表 - MiniBug</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .status-open { @apply bg-red-100 text-red-800; }
        .status-in_progress { @apply bg-yellow-100 text-yellow-800; }
        .status-resolved { @apply bg-green-100 text-green-800; }
        .status-closed { @apply bg-gray-100 text-gray-800; }
        
        .priority-low { @apply bg-blue-100 text-blue-800; }
        .priority-medium { @apply bg-yellow-100 text-yellow-800; }
        .priority-high { @apply bg-orange-100 text-orange-800; }
        .priority-critical { @apply bg-red-100 text-red-800; }
    </style>
</head>
<body class="bg-gray-50">
    <nav class="bg-white shadow-sm border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <a href="/bugs" class="text-xl font-bold text-gray-900">MiniBug</a>
                </div>
                <div class="flex items-center space-x-4">
                    <span id="user-info" class="text-sm text-gray-700"></span>
                    <button onclick="logout()" class="text-sm text-gray-500 hover:text-gray-700">退出</button>
                </div>
            </div>
        </div>
    </nav>
    
    <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <div class="px-4 py-6 sm:px-0">
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-2xl font-bold text-gray-900">Bug列表</h1>
                <a href="/bugs/new" class="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-md text-sm font-medium">
                    新建Bug
                </a>
            </div>
            
            <!-- 过滤器 -->
            <div class="bg-white p-4 rounded-lg shadow mb-6">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                        <select id="statusFilter" class="w-full border border-gray-300 rounded-md px-3 py-2">
                            <option value="">全部</option>
                            <option value="open">打开</option>
                            <option value="in_progress">进行中</option>
                            <option value="resolved">已解决</option>
                            <option value="closed">已关闭</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">项目</label>
                        <select id="projectFilter" class="w-full border border-gray-300 rounded-md px-3 py-2">
                            <option value="">全部</option>
                        </select>
                    </div>
                    <div class="flex items-end">
                        <button onclick="filterBugs()" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-md text-sm font-medium">
                            筛选
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- Bug列表 -->
            <div class="bg-white shadow overflow-hidden sm:rounded-md">
                <ul id="bugList" class="divide-y divide-gray-200">
                    <!-- Bug项目将在这里动态加载 -->
                </ul>
            </div>
            
            <!-- 分页 -->
            <div id="pagination" class="mt-6 flex justify-center">
                <!-- 分页按钮将在这里动态生成 -->
            </div>
        </div>
    </main>

    <script>
        let currentPage = 1;
        let projects = [];
        
        // 加载项目列表
        function loadProjects() {
            $.ajax({
                url: '/api/projects',
                method: 'GET',
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    projects = data;
                    const select = $('#projectFilter');
                    select.empty().append('<option value="">全部</option>');
                    data.forEach(project => {
                        select.append(`<option value="${project.id}">${project.name}</option>`);
                    });
                },
                error: function(xhr) {
                    console.error('Error loading projects:', xhr);
                }
            });
        }
        
        // 加载Bug列表
        function loadBugs(page = 1) {
            const status = $('#statusFilter').val();
            const projectId = $('#projectFilter').val();
            
            let url = `/api/bugs?page=${page}&limit=10`;
            if (status) url += `&status=${status}`;
            if (projectId) url += `&project_id=${projectId}`;
            
            $.ajax({
                url: url,
                method: 'GET',
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    displayBugs(data.bugs);
                    displayPagination(data.total, data.page, data.limit);
                    currentPage = page;
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/login';
                    } else {
                        console.error('Error loading bugs:', xhr);
                        $('#bugList').html('<li class="px-6 py-4 text-center text-red-500">加载失败，请刷新页面重试</li>');
                    }
                }
            });
        }
        
        // 显示Bug列表
        function displayBugs(bugs) {
            const list = $('#bugList');
            list.empty();
            
            if (bugs.length === 0) {
                list.append('<li class="px-6 py-4 text-center text-gray-500">暂无Bug</li>');
                return;
            }
            
            bugs.forEach(bug => {
                const statusClass = `status-${bug.status}`;
                const priorityClass = `priority-${bug.priority}`;
                const statusText = {
                    'open': '打开',
                    'in_progress': '进行中',
                    'resolved': '已解决',
                    'closed': '已关闭'
                }[bug.status] || bug.status;
                
                const priorityText = {
                    'low': '低',
                    'medium': '中',
                    'high': '高',
                    'critical': '紧急'
                }[bug.priority] || bug.priority;
                
                const createdAt = new Date(bug.created_at).toLocaleDateString('zh-CN');
                
                list.append(
                    '<li class="px-6 py-4 hover:bg-gray-50">' +
                        '<div class="flex items-center justify-between">' +
                            '<div class="flex-1">' +
                                '<div class="flex items-center space-x-3">' +
                                    '<a href="/bugs/' + bug.id + '" class="text-lg font-medium text-indigo-600 hover:text-indigo-500">' +
                                        '#' + bug.id + ' ' + bug.title +
                                    '</a>' +
                                    '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ' + statusClass + '">' +
                                        statusText +
                                    '</span>' +
                                    '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ' + priorityClass + '">' +
                                        priorityText +
                                    '</span>' +
                                '</div>' +
                                '<div class="mt-1 text-sm text-gray-500">' +
                                    '<span>项目: ' + bug.project.name + '</span>' +
                                    '<span class="mx-2">•</span>' +
                                    '<span>报告人: ' + bug.reporter.name + '</span>' +
                                    '<span class="mx-2">•</span>' +
                                    '<span>创建时间: ' + createdAt + '</span>' +
                                '</div>' +
                            '</div>' +
                            '<div class="flex items-center space-x-2">' +
                                (bug.pictures && bug.pictures.length > 0 ? 
                                    '<span class="text-xs text-gray-400">📷 ' + bug.pictures.length + '</span>' : '') +
                            '</div>' +
                        '</div>' +
                    '</li>'
                );
            });
        }
        
        // 显示分页
        function displayPagination(total, page, limit) {
            const totalPages = Math.ceil(total / limit);
            const pagination = $('#pagination');
            pagination.empty();
            
            if (totalPages <= 1) return;
            
            let html = '<nav class="flex space-x-2">';
            
            // 上一页
            if (page > 1) {
                html += '<button onclick="loadBugs(' + (page - 1) + ')" class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50">上一页</button>';
            }
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === page) {
                    html += '<span class="px-3 py-2 text-sm font-medium text-white bg-indigo-600 border border-indigo-600 rounded-md">' + i + '</span>';
                } else {
                    html += '<button onclick="loadBugs(' + i + ')" class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50">' + i + '</button>';
                }
            }
            
            // 下一页
            if (page < totalPages) {
                html += '<button onclick="loadBugs(' + (page + 1) + ')" class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50">下一页</button>';
            }
            
            html += '</nav>';
            pagination.html(html);
        }
        
        // 筛选Bug
        function filterBugs() {
            loadBugs(1);
        }
        
        // 退出登录
        function logout() {
            $.ajax({
                url: '/api/logout',
                method: 'POST',
                xhrFields: {
                    withCredentials: true
                },
                success: function() {
                    window.location.href = '/login';
                }
            });
        }
        
        $(document).ready(function() {
            loadProjects();
            loadBugs();
        });
    </script>
</body>
</html>
